let player;
let hls;
let currentVideoElement; // 跟踪当前视频元素

// 初始化播放器
function initPlayer(m3u8Url) {
  console.log("初始化播放器，URL:", m3u8Url);

  // 检查 URL 是否有效
  if (!m3u8Url || !m3u8Url.startsWith("http")) {
    handlePlayerError("无效的视频地址");
    return;
  }

  // 获取或创建视频容器
  const videoContainer = document.querySelector(".video-container");
  if (!videoContainer) {
    handlePlayerError("找不到视频容器");
    return;
  }

  // 销毁现有播放器
  destroyPlayer();

  // 创建新的 video 元素
  const newVideoElement = document.createElement("video");
  newVideoElement.id = "my-video";
  newVideoElement.className = "video-js vjs-default-skin my-video-dimensions";
  newVideoElement.controls = true;
  newVideoElement.preload = "auto";
  newVideoElement.poster = "{{ video.vod_pic }}";
  newVideoElement.innerHTML =
    '<p class="vjs-no-js">您的浏览器不支持HTML5视频，请使用现代浏览器观看。</p>';

  // 清空容器并添加新元素
  videoContainer.innerHTML = "";
  videoContainer.appendChild(newVideoElement);
  currentVideoElement = newVideoElement;

  // 清除之前的错误状态
  const errorMessage = document.querySelector(".error-message");
  if (errorMessage) {
    errorMessage.remove();
  }

  if (Hls.isSupported()) {
    hls = new Hls({
      debug: false,
      enableWorker: true,
      lowLatencyMode: true,
      maxBufferLength: 30,
      maxMaxBufferLength: 60,
      backBufferLength: 10,
    });

    hls.loadSource(m3u8Url);
    hls.attachMedia(newVideoElement);

    player = videojs(newVideoElement, {
      html5: {
        hls: {
          withCredentials: false,
        },
      },
      liveui: true,
      playbackRates: [0.5, 1, 1.25, 1.5, 2],
    });

    hls.on(Hls.Events.MANIFEST_PARSED, function () {
      console.log("视频加载完成，可以播放");
      player.play().catch((error) => {
        console.log("自动播放被阻止:", error);
      });
    });

    hls.on(Hls.Events.ERROR, function (event, data) {
      console.error("HLS 错误:", data);
      if (data.fatal) {
        switch (data.type) {
          case Hls.ErrorTypes.NETWORK_ERROR:
            console.log("网络错误，尝试重新加载...");
            hls.startLoad();
            break;
          case Hls.ErrorTypes.MEDIA_ERROR:
            console.log("媒体错误，尝试恢复...");
            hls.recoverMediaError();
            break;
          default:
            console.log("不可恢复的错误");
            destroyPlayer();
            initPlayer(m3u8Url); // 重新初始化
            break;
        }
      }
    });
  } else if (newVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
    // Safari 原生支持
    newVideoElement.src = m3u8Url;
    player = videojs(newVideoElement);

    newVideoElement.addEventListener("loadedmetadata", function () {
      player.play().catch((error) => {
        console.log("自动播放被阻止:", error);
      });
    });
  } else {
    handlePlayerError("您的浏览器不支持HLS播放");
  }
}

// 销毁播放器
function destroyPlayer() {
  if (player) {
    try {
      player.dispose();
      player = null;
    } catch (e) {
      console.warn("销毁播放器时出错:", e);
    }
  }

  if (hls) {
    try {
      hls.destroy();
      hls = null;
    } catch (e) {
      console.warn("销毁HLS实例时出错:", e);
    }
  }

  // 移除旧的 video 元素
  if (currentVideoElement && currentVideoElement.parentNode) {
    currentVideoElement.parentNode.removeChild(currentVideoElement);
  }
}

// 播放剧集 =======================================================================
function playEpisode(name, url, event) {
  console.log("播放剧集:", name, url);

  try {
    // 更新活跃按钮
    document.querySelectorAll(".episode-btn").forEach((btn) => {
      btn.classList.remove("active");
    });

    if (event && event.target) {
      event.target.classList.add("active");
    } else {
      // 如果没有事件对象，尝试通过其他方式找到按钮
      const buttons = document.querySelectorAll(".episode-btn");
      for (let btn of buttons) {
        if (btn.dataset.url === url) {
          btn.classList.add("active");
          break;
        }
      }
    }

    // 更新播放器
    initPlayer(url);

    // 更新页面标题
    document.title = `${name}`;
  } catch (error) {
    console.error("播放剧集错误:", error);
    handlePlayerError("播放失败");
  }
}

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", function () {
  console.log("页面加载完成，初始化播放器...");

  // 检查 HLS 支持
  if (typeof Hls === "undefined") {
    handlePlayerError("HLS.js 库加载失败");
    return;
  }

  if (typeof videojs === "undefined") {
    handlePlayerError("Video.js 库加载失败");
    return;
  }

  // 自动播放第一集
  const firstEpisode = document.querySelector(".episode-btn");
  if (firstEpisode) {
    const url = firstEpisode.dataset.url;
    if (url && url.trim() !== "") {
      // 添加延迟确保 DOM 完全加载
      setTimeout(() => {
        initPlayer(url);
        firstEpisode.classList.add("active");
      }, 100);
    } else {
      handlePlayerError("视频地址无效");
    }
  } else {
    handlePlayerError("没有找到可播放的剧集");
  }
});

// 错误处理
function handlePlayerError(message) {
  console.error("播放错误:", message);

  const videoContainer = document.querySelector(".video-container");
  if (videoContainer) {
    videoContainer.innerHTML = `
            <div class="error-message">
                <i class="fas fa-exclamation-triangle"></i>
                <p>${message}</p>
                <button onclick="location.reload()">重新加载</button>
            </div>
        `;
  }
}

// 添加重新加载函数
function reloadPlayer() {
  const activeBtn = document.querySelector(".episode-btn.active");
  if (activeBtn) {
    const url = activeBtn.dataset.url;
    destroyPlayer();
    initPlayer(url);
  }
}
